package com.niuniu.rushdorm.service.impl;

import com.niuniu.rushdorm.exception.ReportedException;
import com.niuniu.rushdorm.pojo.entity.Order;
import com.niuniu.rushdorm.pojo.entity.OrderMessage;
import com.niuniu.rushdorm.pojo.vo.UserVO;
import com.niuniu.rushdorm.service.GroupService;
import com.niuniu.rushdorm.service.OrderService;
import com.niuniu.rushdorm.util.MQSender;
import com.niuniu.rushdorm.util.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    GroupService groupService;
    @Autowired
    MQSender mqSender;
    @Autowired
    RedisTemplate redisTemplate;

    private Integer generateId(){
        Integer orderId = redisTemplate.opsForValue().increment("order_cnt",1L).intValue();
        return orderId;
    }
    @Override
    public int createOrder(UserVO userVO, Integer buildingId) {
        Order order = new Order();
        order.setSubmitTime((int)(System.currentTimeMillis()/1000));

        ///
        Long t1 = System.currentTimeMillis();
        ///


        //1. 获取学生所在队伍及成员
        Integer groupId = groupService.getGroupId(userVO.getUid());
        List<Integer> uids;
        ///
        Long t3 = System.currentTimeMillis();
        log.info("查询groupId\t"+(t3-t1));


        //2. 检查团队或学生是否已成功选到宿舍
        if(groupId==null){
            uids = new ArrayList<>();
            Object flag = redisTemplate.opsForValue().get("success_student:"+userVO.getUid());
            if(flag!=null){
                throw ReportedException.build(StatusEnum.STUDENT_SUCCESS);
            }
            uids.add(userVO.getUid());
        }else{
            Object groupFlag = redisTemplate.opsForValue().get("success_group:"+groupId);
            if(groupFlag!=null){
                throw ReportedException.build(StatusEnum.GROUP_SUCCESS);
            }
            uids = groupService.getUids(groupId);
        }
        ///
        Long t2 = System.currentTimeMillis();
        log.info("查询总用时\t"+(t2-t1)+"\t占比\t"+((float)(t3-t1)/(t2-t1)));

        //3.构造消息发送到消息队列
        order.setId(generateId());
        order.setUid(userVO.getUid());
        order.setGroupID(groupId);
        order.setCreateTime((int)System.currentTimeMillis()/1000);
        order.setBuildingID(buildingId);
        order.setStatus(0);
        OrderMessage message = new OrderMessage(uids,userVO.getGender(),userVO.getStudent().getClassId(),order);
        mqSender.sendMessage(message);

        return order.getId();
    }

}
